package com.example.memo2.ui.detail

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.memo2.R
import com.example.memo2.databinding.ItemImagePreviewBinding
import java.io.File

class ImagePreviewAdapter(
    private val onImageRemove: (String) -> Unit
) : ListAdapter<String, ImagePreviewAdapter.ImageViewHolder>(ImageDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val binding = ItemImagePreviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ImageViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ImageViewHolder(private val binding: ItemImagePreviewBinding) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(imagePath: String) {
            // 添加调试日志
            println("正在加载图片: $imagePath")
            val file = File(imagePath)
            println("文件是否存在: ${file.exists()}")
            println("文件大小: ${file.length()} bytes")
            
            // 使用Glide加载本地文件
            Glide.with(binding.root.context)
                .load(file)
                .centerCrop()
                .placeholder(R.drawable.ic_image)
                .error(R.drawable.ic_image)
                .into(binding.imagePreview)
            
            binding.buttonRemoveImage.setOnClickListener {
                onImageRemove(imagePath)
            }
        }
    }
}

class ImageDiffCallback : DiffUtil.ItemCallback<String>() {
    override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
        return oldItem == newItem
    }
} 